package shaw.wifi.nohttp;

import java.io.IOException;

import shaw.wifi.Constants;
import shaw.wifi.NetworkSettingsTaskManager;
import shaw.wifi.network.ConnectionInformation;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class NetworkSettingsGetNewAppInfoTask extends NetworkSettingsNoHttpTask {
	@Override
	protected Integer doInBackground(ConnectionInformation... params) {
		if(!setupSocketConnection()) {
			NetworkSettingsTaskManager.get().clearTasks();
			return null;
		}
		
		boolean result = false;
		if(params[0].set == false) {
			result = getNewAppInfo(params[0]);
			//decide if continue:
			if(result == false) {
				NetworkSettingsTaskManager.get().clearTasks();
			}
		}
		
		publishProgress("App Username: "+ params[0].username);
		publishProgress("App Password: "+ params[0].password);
		
		return null;
	}

	private boolean getNewAppInfo(ConnectionInformation info) {
		publishProgress("Getting app username/password");
		
		if(Constants._APPUSERNAME != null && Constants._APPPASSWORD != null) {
			info.username = Constants._APPUSERNAME;
			info.password = Constants._APPPASSWORD;
			info.set = true;
			return true;
		} else {
			publishProgress("App username/password not found locally, requesting from server");
			//need to retrieve from server
			ShawWifiMessage msg = new ShawWifiMessage(1);
			msg.type = ShawWifiMessage.TYPE_GETAPPCRED;
			msg.header[0] = "action";
			msg.data[0] = "getappcred".getBytes();
			
			try {
				msg.sendEncryptedMessage(oos, encryption);
			} catch (IOException e) {
				e.printStackTrace();
				publishProgress("Unable to get app credentials...");
				return false;
			}
			
			ShawWifiMessage resp = this.waitForCryptMessage();
			if(resp == null) {
				publishProgress("Did not recieve username/password from server");
				return false;
			}
			
			try {
				if(resp.length != 2) throw new UnexpectedMessageException("expected 2 headers");
				if(!resp.header[0].equals("USERNAME")) throw new UnexpectedMessageException("expected header USERNAME" + resp.header[0]);
				if(!resp.header[1].equals("PASSWORD")) throw new UnexpectedMessageException("expected header PASSWORD" + resp.header[1]);
				
				Constants._APPUSERNAME = info.username = new String(resp.data[0]);
				Constants._APPPASSWORD = info.password = new String(resp.data[1]);
				
				SharedPreferences sp = Constants._SHAREDPREFS;
				Editor edit = sp.edit();
				edit.putString("APPUSERNAME", Constants._APPUSERNAME);
				edit.putString("APPPASSWORD", Constants._APPPASSWORD);
				edit.commit();
				
				return true;
			} catch(UnexpectedMessageException e) {
				e.printStackTrace();
				publishProgress("Received unexpected message from server, please make sure you have the most recent version of the application");
				return false;
			}
		}
	}
}
